package com.example.myapp61.Mfragment;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AlertDialogLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ejlchina.okhttps.HTTP;
import com.example.myapp61.MySqlDB.DBMainHepler;
import com.example.myapp61.R;
import com.example.myapp61.Util.ToasUtil;
import com.example.myapp61.Util.myutil;
import com.example.myapp61.xiaoye.top.ClassBase;
import com.example.myapp61.xiaoye.top.RecyclerViewAdapter;
import com.xuexiang.xutil.data.SPUtils;

import org.jsoup.Jsoup;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class fragment3 extends Fragment {
    private Context mContext;
    private static final String TAG = "测试";
    //登录成功欢迎文本,默认不显示
    private TextView textView;
    //登录按钮
    private Button login;
    //连接相关
    private String stuName;
    private String __VIEWSTATE = "";
    private Map<String,String> cookies = new HashMap<>();
    private Connection connection;
    private Connection.Response response;
    private Document document;
    //验证码图片
    private ImageView mImageView;
    //用户输入的学号，密码，验证码
    private EditText user,pwd,code;
    //数据库
    private DBMainHepler insertDB;
    private SQLiteDatabase db;
    //登录窗口
    private AlertDialog mAlertDialog;
    private AlertDialog.Builder builder;
    private RecyclerView mRecyclerView;
    private RecyclerViewAdapter mAdapter;
    private TextView anew;
    private CheckBox mCheckBox;
    private SharedPreferences mPreferences;

    
    
    
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mContext = context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_fragment3, null);
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initView(View view) {
        mPreferences = SPUtils.getSharedPreferences("androidId");
        anew = view.findViewById(R.id.anew);
        login = view.findViewById(R.id.login);
        textView =view.findViewById(R.id.welcome);
        mRecyclerView = view.findViewById(R.id.recycler);
        insertDB = new DBMainHepler(mContext,"Class2.db",null,1);
        db = insertDB.getWritableDatabase();
        anew.setVisibility(View.GONE);
        //事件设置初始化
        setEve();
        //初始化课程表
        initCoures();
    }

    private void initCoures() {
        Boolean is =  SPUtils.getBoolean(SPUtils.getSharedPreferences("androidId"),"getCouresSucceed",false);
          if (is){
              Log.d(TAG, "initCoures: 可以执行了");
              login.setVisibility(View.GONE);
              textView.setVisibility(View.VISIBLE);
              anew.setVisibility(View.VISIBLE);
              setRecyclerView();
          }
    }

    //事件设置初始化
    private void setEve() {
        anew.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initConn();
            }
        });
        /**
         * 登录
         */
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initConn();
            }
        });
    }

    private void initConn() {
        connectIndex();
        myutil.trustEveryone();
        builder = new AlertDialog.Builder(mContext);
        View view1 = LayoutInflater.from(mContext).inflate(R.layout.layout_login, null);
        Button button = view1.findViewById(R.id.login_submit);
        user = view1.findViewById(R.id.user);
        pwd = view1.findViewById(R.id.pwd);
        code = view1.findViewById(R.id.code);
        //记住密码
        mCheckBox = view1.findViewById(R.id.rememberPwd);
        if (SPUtils.contains(mPreferences,"username")){
            user.setText(SPUtils.getString(mPreferences,"username",null));
            pwd.setText(SPUtils.getString(mPreferences,"userpwd",null));
            mCheckBox.setChecked(SPUtils.getBoolean(mPreferences,"rememberPwd",false));
        }
        //关闭登录窗口按钮
        ImageView imageView =  view1.findViewById(R.id.dis);
        mImageView = view1.findViewById(R.id.img);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAlertDialog.dismiss();
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mCheckBox.isChecked()){
                    //用户记住密码，存入本地
                    SPUtils.putString(mPreferences,"username",user.getText().toString());
                    SPUtils.putString(mPreferences,"userpwd",pwd.getText().toString());
                    SPUtils.putBoolean(mPreferences,"rememberPwd",mCheckBox.isChecked());
                }else{
                    SPUtils.remove(mPreferences,"username");
                    SPUtils.remove(mPreferences,"userowd");
                    SPUtils.remove(mPreferences,"rememberPwd");
                }
                xiaoye_Login(user.getText().toString(),pwd.getText().toString(),code.getText().toString());
            }
        });
        mAlertDialog = builder
                .setCancelable(false)
                .setView(view1).create();
        mAlertDialog.show();
    }

    /**
     * 登录
     * @param stuNum  学号
     * @param pwd  密码
     * @param checkCode  验证码
     */
    private void xiaoye_Login(final String stuNum,String pwd,String checkCode) {

        Map<String, String> datas = new HashMap<>();
        datas.put("__VIEWSTATE",__VIEWSTATE);
        datas.put("TextBox1",stuNum);
        datas.put("TextBox2",pwd);
        datas.put("TextBox3",checkCode);
        datas.put("RadioButtonList1","%D1%A7%C9%FA");
        datas.put("Button1","");
        datas.put("lbLanguage","");
        final Map<String, String> datas1 = datas;
        final Message message = new Message();
        message.what = 2;
        new Thread(new Runnable() {
            @Override
            public void run() {
                connection = Jsoup.connect("https://jwc.mmpt.edu.cn/");
                connection.header("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
                try {
                    response = connection.postDataCharset("GB2312").ignoreContentType(true).method(Connection.Method.POST)
                            .data(datas1).cookies(cookies).execute();
                    document = response.parse();
                    if (document.title().equals("登录")){ mHandler.sendEmptyMessage(12);
                    }else{
                        //登录成功
                        stuName = document.getElementById("xhxm").html();
                        Log.d(TAG, "run: "+stuNum);
                        //删除表
                        db.execSQL("DROP TABLE class");
                        db.execSQL("create table class(id integer(2),week integer(2),name varchar(40),site varchar(10))"); //重新创建
                        mHandler.sendEmptyMessage(11);
                        Log.d(TAG, "run: "+document.title());
                        getStudentMessage();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 解析课表
     * @throws IOException
     */
    private void getStudentMessage() throws IOException{
        String infoURL = "https://jwc.mmvtc.cn/xskbcx.aspx?xh="+
                user.getText().toString()+"&xm="+
                URLEncoder.encode(stuName,"GB2312")+
                "&gnmkdm=N121603";
        Log.d(TAG, "getStudentMessage: "+infoURL);
        connection = Jsoup.connect(infoURL);
        response = connection.ignoreContentType(true).method(Connection.Method.GET)
                .userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0")
                .referrer("https://jwc.mmvtc.cn/xs_main.aspx?xh="+user.getText().toString())
                .cookies(cookies).postDataCharset("GB2312").timeout(5000).execute();


        /**
         * 解析开始
         */
        document = Jsoup.parse(response.body());
        Element Table1 =  response.parse().getElementById("Table1");
        //Log.d(TAG, "getStudentMessage: "+Table1.toString());
        //得到所有行
        Elements trs =  Table1.getElementsByTag("tr");
        for (int i = 0; i < trs.size(); i++) {

            //1,3,5,6,8,10
            //只处理行号为2（第一节）,4(第三节)，6（第五节）,7(第6节),9(第8节),11,(第10节)
            if (i == 2 || i==4 || i==6 || i==7 || i==9||i==11){
                Log.d(TAG, "**************************************************");
                //得到显示第一节课的第一行
                Element e1 =  trs.get(i);

                //得到所有列
                Elements tds = e1.getElementsByTag("td");
                if (i==2||i==7||i==11){
                    tds.remove(0);
                }
                for (int j = 0;j<tds.size();j++){
                    String msg = tds.get(j).text();
                    //清除上午，下午，晚上那一行

                    //判断是否有课程
                    if (msg.length() == 1){
                        insertDB(i,j,"\uD83D\uDE01\uD83D\uDE01木有课程");
                        continue; //跳过循环
                    }

//                    Log.d(TAG, "getStudentMessage: "+"是不被执行？？？？？？？");

                    ////处理一个td里的字符，如：计算机组成原理 2节/周(1-17) 张凤英 田师208
                    String strings[] = msg.split(" "); //用于把字符串分割成数组
//                    int duringNum = Integer.parseInt(strings[1]);

                    if (strings.length>=4){
//                        Log.d(TAG, "getStudentMessage: "+strings.length);
//                        Log.d(TAG, "getStudentMessage: "+msg);
//                        Log.d(TAG, "课程名称: "+strings[0]);
//                        Log.d(TAG, "getStudentMessage: "+strings[0]+strings[1]);
                        if (strings.length>=4){
                            String class_name = getcalssname(strings);
                            String site = getSite(strings);
//                            Log.d(TAG, "getStudentMessage: 课程名称："+class_name+j+" "+i);
//                            Log.d(TAG, "getStudentMessage: 地点："+strings[strings.length-1]);
//                            Log.d(TAG, "getStudentMessage: 判断是否有调整"+site);
                            insertDB(i,j,class_name,site);
                        }
                    }
                }
            }
        }
        //tr循环结束
        mHandler.sendEmptyMessage(111);
    }

    /**
     * 获取cookies
     */
    private void connectIndex() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    connection = Jsoup.connect("https://jwc.mmpt.edu.cn/");
                    response = connection.execute();
                    connection.get();
                    cookies = response.cookies();
                    document = Jsoup.parse(response.body());
                    for (Element element:document.getElementsByTag("input")){
                        if (element.attr("name").equals("__VIEWSTATE")){
                            __VIEWSTATE = element.val();
                            break;
                        }
                    }
                    downloadCheckcode();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 获取验证码
     */
    private void downloadCheckcode() {
        Log.i(TAG, "onCreate: "+__VIEWSTATE);
        Log.i(TAG, "onCreate: "+cookies);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = "https://jwc.mmpt.edu.cn/CheckCode.aspx";
                try {
                    response = Jsoup.connect(url).cookies(cookies).ignoreContentType(true)
                            .userAgent("Mozilla").method(Connection.Method.GET).timeout(5000).execute();
                    byte[] bytes = response.bodyAsBytes();
                    Message message = new Message();
                    message.what = 1;
                    message.obj = bytes;
                    Log.i(TAG, "run: "+bytes.length);
                    mHandler.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    /**
     * 课程名称获取
     * @param strings
     * @return
     */
    private String getSite(String[] strings) {
        if (strings[strings.length-1].indexOf("(")==0){
            return strings[strings.length-2];
        }
        return strings[strings.length-1];
    }

    /**
     * 存入数据库
     * @param i  第几节课
     * @param j  星期几
     * @param name   课程名称
     */
    private void insertDB(int i,int j, String name) {
        ContentValues c = new ContentValues();
        c.put("id",i);
        c.put("week",j);
        c.put("name",name);
        db.insert("class",null,c);
    }

    /**
     * 同上,加入上课地点
     * @param i
     * @param j
     * @param name
     * @param site  地点
     */
    private void insertDB(int i,int j, String name,String site) {
        ContentValues c = new ContentValues();
        c.put("id",i);
        c.put("week",j);
        c.put("name",name);
        c.put("site",site);
        db.insert("class",null,c);
    }

    /**
     * 特殊课程处理
     * @param strings
     * @return
     */
    private String getcalssname(String[] strings) {
        if ("JavaWeb应用开发".equals(strings[0]+strings[1])) {
            return strings[0]+strings[1];
        }
        return strings[0];
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1: //获取验证码成功
                    byte[] b = (byte[]) msg.obj;
                    Log.i(TAG, "handleMessage: "+b.length);
                    final Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.length);
                    mImageView.setImageBitmap(bmp);
                    break;
                case 11: //登录成功
                    Toast.makeText(mContext, "登录成功",Toast.LENGTH_SHORT).show();
                    mAlertDialog.dismiss();
                    login.setVisibility(View.GONE);
                    textView.setVisibility(View.VISIBLE);
                    anew.setVisibility(View.VISIBLE);
                    break;
                case 12://登录失败
                    ToasUtil.showMes(mContext,"登录失败,请退出重新登录,很抱歉！");
                    mAlertDialog.dismiss();
                    break;
                case 111: //获取课程表结束
                    setRecyclerView();
                    break;
            }
        }
    };
    //获取课程表结束
    private void setRecyclerView() {
        ArrayList<ClassBase> list = new ArrayList<>();
        db = insertDB.getReadableDatabase();
        Cursor cursor =  db.query("class",null,null,null,null,null,null);
        if (cursor.moveToNext()){
            do {
                int id = cursor.getInt(cursor.getColumnIndex("id"));
                int week = cursor.getInt(cursor.getColumnIndex("week"));
                String name = cursor.getString(cursor.getColumnIndex("name"));
                String site = cursor.getString(cursor.getColumnIndex("site"));
                list.add(new ClassBase(id,week,name,site));
            }while (cursor.moveToNext());
        }
        mAdapter = new RecyclerViewAdapter(mContext,list);
        mRecyclerView.setLayoutManager(new GridLayoutManager(mContext,7));
        mRecyclerView.setAdapter(mAdapter);
        //获取课程表结束,把信息写入到本地
        SPUtils.putBoolean(SPUtils.getSharedPreferences("androidId"),"getCouresSucceed",true);
    }
}
